﻿using Android.App;
using Android.Widget;
using Android.OS;
using Android.Webkit;
using Android.Net.Http;
using System.Net;
using System.Net.Sockets;
using System;
using System.Text;
using System.IO;

namespace YDArrangement
{
    [Activity(Label = "35-356-一丹排队叫号大屏显示", MainLauncher = true, Icon = "@drawable/ydIcon")]
    public class MainActivity : Activity
    {
        private byte[] buffer = new byte[1024 * 1024 * 2];
        protected override void OnCreate(Bundle savedInstanceState)
        {
            this.SetTheme(Android.Resource.Style.ThemeNoTitleBarFullScreen);//全屏并且无标题栏，必须在OnCreate前面设置。
            this.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;//横屏，禁止竖屏
            base.OnCreate(savedInstanceState);
            //BootReceiver br = new BootReceiver();
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
        }

        /// <summary>
        /// 跳转回来刷新数据
        /// </summary>
        protected override void OnResume()
        {
            base.OnResume();
            GetListData();
            //Thread th = new Thread(Receive);
            //th.Start();

        }


        public void Receive()
        {
            var ipstring = GetLocalIp();
            var ip = IPAddress.Parse(ipstring);
            TcpListener tcpl = new TcpListener(ip, 9701);//定义一个TcpListener对象监听本地的1111端口
            tcpl.Start();//监听开始
            while (true)
            {
                try
                {
                    Socket s = tcpl.AcceptSocket();//挂起一个Socket对象
                    GetListData(); //测试
                    string remote = s.RemoteEndPoint.ToString();//获取发送端的IP及端口转为String备用
                    Byte[] stream = new Byte[1024];
                    int strlength = s.Receive(stream);//接收发送端发过来的数据,写入字节数组
                                                      //BGW_Handle.ReportProgress(1, "接收来自[" + remote + "]信息");
                    string _data = Encoding.UTF8.GetString(stream, 0, strlength);//将字节数据数组转为String
                    #region 添加数据传输
                    string url = "http://49.4.8.98:8081/api/Values";      //设定好发送地址就可以发包了
                    string result = PostHttpResponse(_data, url);
                    if (result == "success")
                    {
                        GetListData();
                    }
                    #endregion 
                }
                catch (Exception ex)
                { Toast.MakeText(this, ex.ToString(), ToastLength.Short).Show(); }
            }
            tcpl.Stop();//停止监听

        }


        /// <summary>
        /// 获取数据
        /// </summary>
        private void GetListData()
        {
            WebView _webview = FindViewById<WebView>(Resource.Id.webView1);
            _webview.LoadUrl("http://49.4.8.98:8081/D35_Show_E1_3");
            _webview.Settings.JavaScriptEnabled = true;
            _webview.Settings.SetSupportZoom(true);
            _webview.Settings.BuiltInZoomControls = true;
            #region ZFX 自适应防止网页超屏显示
            _webview.Settings.UseWideViewPort = true;
            _webview.Settings.DisplayZoomControls = false;
            _webview.Settings.LoadWithOverviewMode = true;
            _webview.Settings.SetLayoutAlgorithm(WebSettings.LayoutAlgorithm.SingleColumn);
            #endregion
            _webview.SetWebViewClient(new ExtWebViewClient());

        }

        //IPAddress ip;
        //IPEndPoint ipEnd;
        //Socket socket;
        //private void Send()
        //{
        //    try
        //    {
        //        ip = IPAddress.Parse("192.168.43.166");//接收端所在IP
        //        ipEnd = new IPEndPoint(ip, 1111);//接收端所监听的接口
        //        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化一个Socket对象
        //        if (!socket.Connected)
        //        {
        //            socket.Connect(ipEnd);//连接指定IP&端口
        //        }
        //        socket.Send(Encoding.UTF8.GetBytes("ok"));//发送数据
        //                                                  //while (true)//定义一个循环接收返回数据
        //                                                  //{
        //                                                  //    byte[] data = new byte[1024];
        //                                                  //    socket.Receive(data);//接收返回数据
        //                                                  //    string stringData = Encoding.UTF8.GetString(data);
        //                                                  //    if (!string.IsNullOrWhiteSpace(stringData))
        //                                                  //    {
        //                                                  //        Console.Write(stringData);
        //                                                  //        break;
        //                                                  //    }
        //                                                  //}
        //        socket.Shutdown(SocketShutdown.Both);
        //        socket.Close();//关闭Socket

        //    }
        //    catch (Exception ex)
        //    {
        //        //MessageBox.Show(ex.ToString());
        //    }

        //}



        public string GetLocalIp()
        {
            ///获取本地的IP地址
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }


        /// <summary>  
        /// 模拟POST提交  
        /// </summary>  
        /// <param name="url">请求地址</param>  
        /// <param name="xmlParam">xml参数</param>  
        /// <returns>返回结果</returns>  
        public static string PostHttpResponse(string xmlParam, string url)
        {
            #region 文本获取post方法
            xmlParam = "value=" + xmlParam;
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            myHttpWebRequest.Method = "POST";
            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            // Encode the data  
            byte[] encodedBytes = Encoding.UTF8.GetBytes(xmlParam);
            myHttpWebRequest.ContentLength = encodedBytes.Length;

            // Write encoded data into request stream  
            Stream requestStream = myHttpWebRequest.GetRequestStream();
            requestStream.Write(encodedBytes, 0, encodedBytes.Length);
            requestStream.Close();

            HttpWebResponse result;

            try
            {
                result = (HttpWebResponse)myHttpWebRequest.GetResponse();
            }
            catch
            {
                return string.Empty;
            }

            if (result.StatusCode == HttpStatusCode.OK)
            {

                Stream mystream = result.GetResponseStream();
                using (StreamReader reader = new StreamReader(mystream))
                {
                    return reader.ReadToEnd();
                }


            }
            return null;
            #endregion
        }

        public class ExtWebViewClient : WebViewClient
        {
            public override void OnReceivedSslError(WebView view, SslErrorHandler handler, SslError error)
            {
                handler.Proceed();
                //base.OnReceivedSslError(view, handler, error);
            }
        }


    }
}

